//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by Fernflower decompiler)
//

package com.wsd.smartcarwasher.controller;

import com.github.pagehelper.PageHelper;
import com.wsd.smartcarwasher.configuration.GetSessionConfig;
import com.wsd.smartcarwasher.constans.ResultState;
import com.wsd.smartcarwasher.dao.CardRecordMapper;
import com.wsd.smartcarwasher.dao.UserCardMapper;
import com.wsd.smartcarwasher.domain.*;
import com.wsd.smartcarwasher.service.*;
import com.wsd.smartcarwasher.util.*;
import io.swagger.annotations.*;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.*;

@Api(
        tags = {"用户洗车订单相关接口"}
)
@Controller
@CrossOrigin
public class OrderController {
    private static final Logger logger = LoggerFactory.getLogger(OrderController.class);
    @Resource
    private OrderService orderService;
    @Resource
    private WxService wxService;
    @Resource
    private StatisticService statisticService;
    @Resource
    private WxPayService wxPayService;
    @Resource
    private CardService cardService;
    @Resource
    private UserInfoService userInfoService;
    @Resource
    private CardRecordMapper cardRecordDao;
    @Resource
    private UserCouponService userCouponService;
    @Resource
    private SysDicService sysDicService;
    @Resource
    private HttpServletRequest request;
    @Resource
    private UserCardMapper userCardMapper;
    @Lazy
    @Resource
    private MachineService machineService;
    @Resource
    @Lazy
    private PriceTimeService priceTimeService;
    @Resource
    @Lazy
    private PartnerService partnerService;
    @Resource
    private PriceService priceService;
    @Resource
    private CardOrderService cardOrderService;

    @ApiOperation(
            value = "创建订单",
            notes = "小程序-订单相关接口",
            produces = "application/json",
            response = ModelMap.class
    )
    @ApiImplicitParam(
            name = "orderInfo",
            value = "订单信息",
            required = true,
            dataType = "OrderInfo"
    )
    @RequestMapping(
            value = {"/v1/order"},
            method = {RequestMethod.POST},
            produces = {"application/json; charset=utf-8"}
    )
    @ResponseBody
    public ModelMap createOrder(@RequestBody OrderInfo orderInfo, HttpServletRequest request) {

        String sessionId = request.getHeader("authorization");
        UserInfo user = this.wxService.getUserInfoBySessionId(sessionId);
        if (user == null) {
            return ReturnUtil.Error(ResultState.GET_USER_INFO_FAILED.getMsg());
//
//        String sessionId = request.getHeader("authorization");
//        UserInfo user = this.wxService.getUserInfoBySessionId(sessionId);
//        if (user == null) {
//            return ReturnUtil.Error(ResultState.GET_USER_INFO_FAILED.getMsg(), 703
//            );
        }
        else if (orderInfo.getOrderPrice() == null) {
            return ReturnUtil.Error(ResultState.ORDER_TOTAL_PRICE_IS_NULL.getMsg());
        } else if (orderInfo.getServiceId() == null) {
            return ReturnUtil.Error(ResultState.ORDER_SERVICE_ID_IS_NULL.getMsg());
        } else if (orderInfo.getMachineId() == null) {
            return ReturnUtil.Error(ResultState.ORDER_MACHINE_ID_IS_NULL.getMsg());
        } else if (orderInfo.getPayWayCode() == 2 && orderInfo.getCardId() == null) {
            return ReturnUtil.Error(ResultState.ORDER_CARD_ID_IS_EMPTY.getMsg());
        } else {
            orderInfo.setUserId(String.valueOf(user.getUserId()));
            //判断优惠卷是否在此机器上可用
            if (StringUtils.isNotBlank(orderInfo.getUserCouponId())) {
                UserCoupon userCoupon = userCouponService.selectUserCoupon(orderInfo.getUserCouponId());
                if (userCoupon.getEndTime().before(new Date())) {
                    return ReturnUtil.Error("优惠卷已过期!!");
                }
                if (userCoupon.getUseNum() == 0) {
                    return ReturnUtil.Error("优惠卷已使用!!");
                }
                if (userCoupon.getCoupon().getAvailableMachines().equals("ALLMACHINS")) {
                } else {
                    String[] machineIds = userCoupon.getCoupon().getAvailableMachines().split(",");
                    boolean flag = Arrays.asList(machineIds).contains(String.valueOf(orderInfo.getMachineId()));
                    if (!flag) {
                        return ReturnUtil.Error("该优惠卷无法在此机器上使用!!");
                    }
                }
            }
            //判断会员卡是否在此机器上可用
            if (2 == orderInfo.getPayWayCode()) {
                int cardId = orderInfo.getCardId();
                int serviceId = orderInfo.getServiceId();
                String ucId = orderInfo.getUcId();
                int machineId = orderInfo.getMachineId();
                //新增用户会员卡id
                orderInfo.setCardUcId(ucId);
                UserCard userCard = this.cardService.queryUserCardByServiceId(user.getUserId(), cardId, serviceId, ucId);
                if (userCard == null) {
                    return ReturnUtil.Error("会员卡不支持此种洗车模式!!");
                }
                if (userCard.getValidDate().before(new Date())) {
                    return ReturnUtil.Error("会员卡已经过期!!");
                }
                WashServiceWithTimes service = (WashServiceWithTimes) userCard.getServices().stream().filter((s) -> {
                    return serviceId == orderInfo.getServiceId();
                }).findFirst().orElse(null);
                if (service.getTimes() == 0) {
                    return ReturnUtil.Error("次数已用完!!");
                }

                //查询用户是否今天持促销会员卡并且消费过（如果没有消费或者没有查到，给予通过）
                boolean cardFlag= this.orderService.queryCardIsActivityAndUsed(user.getUserId(),ucId);
                if(cardFlag)
                {
                    return ReturnUtil.Error("该类型会员卡一天只可使用一次哦!!");
                }
                //查询用户当前是否45秒之内有尚未启动的订单
                boolean usedFlag= this.orderService.queryCreatedOrder(user.getUserId());
                if(usedFlag)
                {
                    return ReturnUtil.Error("当前操作过于频繁了哦,请稍后重试");
                }
                boolean flag = this.cardService.testUserCard(userCard, machineId);
                if (!flag) {
                    return ReturnUtil.Error("该会员卡无法在此机器上使用!!");
                }
            }
            //判断余额支付
            if(3==orderInfo.getPayWayCode()){
                orderInfo.setCardUcId(null);
                orderInfo.setCarId(null);
                orderInfo.setCardUcId(null);
                if(StringUtil.isNullOrEmpty(user.getBalance()))
                {
                    user.setBalance(BigDecimal.ZERO);
                }
                if(user.getBalance().compareTo(orderInfo.getOrderPrice())<0)
                {
                    return ReturnUtil.Error("余额不足,请充值！！");
                }
            }
            //去操作优惠卷了
            int changeRows = this.orderService.createOrder(orderInfo);

            if (changeRows == 0) {
                return ReturnUtil.Error(ResultState.CREATE_PAY_ORDER_FAIL.getMsg());
            } else {
                if (orderInfo.getPayWayCode() != null) {
                    //威信支付
                    if (1 == orderInfo.getPayWayCode())
                    {
                        if (BigDecimal.ZERO.compareTo(orderInfo.getPayPrice()) < 0) {
                            String clientIP = CommonUtil.getClientIp(request);
                            return this.wxPayService.payByWx(user.getOpenid(), clientIP, orderInfo);
                        }
                        this.orderService.payFinishOrder(orderInfo);
                        return ReturnUtil.Success(ResultState.ORDER_PAY_SUCCEED.getMsg(), orderInfo);
                    }

                    else {
                        //会员卡订单
                        if (2 == orderInfo.getPayWayCode()) {
                            //查询会员卡购买的订单记录表
                            CardRecord cardRecord = this.cardRecordDao.getCardRecordByUcid(orderInfo.getUcId());
                            //之前的会员卡购买用户在该表中没有对应信息
                            if (cardRecord != null) {
                                if (cardRecord.getFirstTimes() == null) {
                                    this.cardRecordDao.updateFirstUseCard(cardRecord.getId());
                                }
                            }

                            Card card = this.cardService.queryCardByCardId(orderInfo.getCardId());
                            //该会员卡为折扣会员卡
                            if (card.getType() == 2) {

                                orderInfo.setPayPrice(orderInfo.getOrderPrice().multiply(card.getCardRate()));
                                logger.info("订单价格为+"+orderInfo.getPayPrice());
                                try{
                                    this.orderService.completeOrderCardByPayPrice(orderInfo);
                                }catch (Exception e)
                                {
                                    logger.info("订单会员卡折扣后价格为+"+orderInfo.getPayPrice());
                                }
                                if (BigDecimal.ZERO.compareTo(orderInfo.getPayPrice()) < 0)
                                {
                                    String clientIP = CommonUtil.getClientIp(request);
                                    return this.wxPayService.payByWx(user.getOpenid(), clientIP, orderInfo);
                                }
                                this.cardService.payByRateCard(user.getUserId(), orderInfo);
                                this.orderService.payFinishOrder(orderInfo);

                                return ReturnUtil.Success(ResultState.ORDER_PAY_SUCCEED.getMsg(), orderInfo);
                            }
                            return this.cardService.payByCard(user.getUserId(), orderInfo);
                        }
                        else if(3==orderInfo.getPayWayCode())
                        {
                            this.orderService.payFinishOrder(orderInfo);
                        }
                    }
                } else {
                    logger.info("payWayCode is null");
                }
                return ReturnUtil.Success(ResultState.CREATE_PAY_ORDER_SUCCESS.getMsg(), orderInfo);
            }
        }
    }

    @ApiOperation(
            value = "查询用户创建的洗车订单",
            notes = "小程序-订单相关接口",
            produces = "application/json",
            response = ModelMap.class
    )
    @RequestMapping(
            value = {"/v1/user_orders"},
            method = {RequestMethod.GET},
            produces = {"application/json; charset=utf-8"}
    )
    @ResponseBody
    public ModelMap queryUserOrders(HttpServletRequest request) {
        String sessionId = request.getHeader("authorization");
        UserInfo user = this.wxService.getUserInfoBySessionId(sessionId);
//        UserInfo user=this.userInfoService.findByOpenId("o7AZa5GY0YkdDjQMzL-jAN1t64MQ");
        List<OrderInfo> orderInfoList=this.statisticService.queryUserOrder(user.getUserId(),null);
        if(!StringUtil.isNullOrEmpty(orderInfoList))
        {
            for (OrderInfo o:orderInfoList
                 ) {
                if(!StringUtil.isNullOrEmpty(o.getConsumed()))
                {
                    o.setConsumed(1);
                }
                if(!StringUtil.isNullOrEmpty(o.getPayPrice()))
                {
                    o.setPayPrice(o.getPayPrice().setScale(2, RoundingMode.HALF_UP));
                }
                if(!StringUtil.isNullOrEmpty(o.getOrderPrice()))
                {
                    o.setOrderPrice(o.getOrderPrice().setScale(2, RoundingMode.HALF_UP));
                }
            }
        }
        return user == null ? ReturnUtil.Error(ResultState.GET_USER_INFO_FAILED.getMsg()) : ReturnUtil.Success(ResultState.QUERY_USER_ORDERS_SUCCESS.getMsg(),orderInfoList);
    }



    //2021.02.25 yangtao 计算当前用户的优惠券和洗车券
    @ApiOperation(
            value = "查询有没有最优惠的下单方案",
            notes = "小程序-订单方案相关接口",
            produces = "application/json",
            response = ModelMap.class
    )
    @RequestMapping(
            value = {"/v1/queryDiscountWay"},
            method = {RequestMethod.GET},
            produces = {"application/json; charset=utf-8"}
    )
    @ResponseBody
    public ModelMap queryDiscountWay(@RequestParam(value = "machineId", required = false) String machineId,
                                     @RequestParam(value = "serviceId", required = false) Integer serviceId,
                                     HttpServletRequest request) {
        String sessionId = request.getHeader("authorization");
        UserInfo user = this.wxService.getUserInfoBySessionId(sessionId);
//        UserInfo user = this.userInfoService.findByMobile("17791961563");
        Price priceEntity=this.priceService.getPriceByServiceId(serviceId);
        Map<String,Object> map=new HashMap<>();
        if(user==null)
        {
            return ReturnUtil.Success(ResultState.QUERY_USER_ORDERS_SUCCESS.getMsg());
        }
        //查询用户名下的最优的优惠券
        CouponEntity couponEntity=userCouponService.getAllUnusedUserFullCoupons(user.getUserId(),priceEntity.getNowPrice(),machineId);
        if(!StringUtil.isNullOrEmpty(couponEntity))
        {
            if(couponEntity.getType()==2)
            {
                couponEntity.setCouponPrice(couponEntity.getCouponRate().multiply(priceEntity.getNowPrice()));
            }
        }
        System.out.println("会员卡查询进程");
        //查询用户名下的最优折扣会员卡
        UserCardEntity cardEntity= cardService.queryDiscountCard(user.getUserId(), serviceId,machineId);
        if(!StringUtil.isNullOrEmpty(cardEntity))
        {
            if(cardEntity.getType()==1)
            {
                map.put("type","card");
                UserCard card=this.cardService.queryUserCard(user.getUserId(), cardEntity.getCardId());
                if(!StringUtil.isNullOrEmpty(card))
                {
                    card.setCard(this.cardService.queryCardByCardId(cardEntity.getCardId()));
                    card.setCardOrder(cardOrderService.queryOrderInfoByUcId(cardEntity.getUcId()));
                    map.put("cardInfo",card);
                }
                return ReturnUtil.Success("查询成功",map);
            }
            if(cardEntity.getType()==2)
            {
                cardEntity.setPrice((BigDecimal.ONE.subtract(cardEntity.getCardRate())).multiply(priceEntity.getNowPrice()));
                if(couponEntity!=null&&couponEntity.getType()==2)
                {
                    if(cardEntity.getCardRate().compareTo(couponEntity.getCouponRate())<0)
                    {
                        map.put("type","card");
                        UserCard card=this.cardService.queryUserCard(user.getUserId(), cardEntity.getCardId());
                        if(!StringUtil.isNullOrEmpty(card))
                        {
                            card.setCard(this.cardService.queryCardByCardId(cardEntity.getCardId()));
                            card.setCardOrder(cardOrderService.queryOrderInfoByUcId(cardEntity.getUcId()));
                            map.put("cardInfo",card);
                        }
                        return ReturnUtil.Success("查询成功",map);
                    }else if(cardEntity.getCardRate().compareTo(couponEntity.getCouponRate())==0)
                    {
                        return ReturnUtil.Success("查询成功",compareValid(cardEntity,couponEntity));
                    }
                    else{
                        map.put("type","coupon");
                        map.put("couponInfo",userCouponService.getUserCouponByIdAndUserId(Integer.parseInt(couponEntity.getCouponId()),user.getUserId()));
                        return ReturnUtil.Success("查询成功",map);
                    }
                }
                else if(couponEntity!=null&&couponEntity.getType()==1)
                {

                    if((BigDecimal.ONE.subtract(cardEntity.getCardRate()).multiply(priceEntity.getNowPrice())).compareTo(couponEntity.getCouponPrice())>0)
                    {
                        map.put("type","card");
                        UserCard card=this.cardService.queryUserCard(user.getUserId(), cardEntity.getCardId());
                        if(!StringUtil.isNullOrEmpty(card))
                        {
                            card.setCard(this.cardService.queryCardByCardId(cardEntity.getCardId()));
                            card.setCardOrder(cardOrderService.queryOrderInfoByUcId(cardEntity.getUcId()));
                            map.put("cardInfo",card);
                        }
                        return ReturnUtil.Success("查询成功",map);
                    } else if((BigDecimal.ONE.subtract(cardEntity.getCardRate()).multiply(priceEntity.getNowPrice())).compareTo(couponEntity.getCouponPrice())==0)
                    {

                        return ReturnUtil.Success("查询成功",compareValid(cardEntity,couponEntity));
                    }
                    else{
                        map.put("type","coupon");
                        map.put("couponInfo",userCouponService.getUserCouponByIdAndUserId(Integer.parseInt(couponEntity.getCouponId()),user.getUserId()));
                        return ReturnUtil.Success("查询成功",map);
                    }
                }
                else
                {
                    map.put("type","card");
                    UserCard card=this.cardService.queryUserCard(user.getUserId(), cardEntity.getCardId());
                    if(!StringUtil.isNullOrEmpty(card))
                    {
                        card.setCard(this.cardService.queryCardByCardId(cardEntity.getCardId()));
                        card.setCardOrder(cardOrderService.queryOrderInfoByUcId(cardEntity.getUcId()));
                        map.put("cardInfo",card);
                    }
                    return ReturnUtil.Success("查询成功",map);
                }
            }
        }
        map.put("type","coupon");
        if(StringUtil.isNullOrEmpty(couponEntity))
        {
            return ReturnUtil.Success("查询成功");
        }
        map.put("couponInfo",userCouponService.getUserCouponByIdAndUserId(Integer.parseInt(couponEntity.getCouponId()),user.getUserId()));
        return ReturnUtil.Success("查询成功",map);
    }


    /**
     * 比较两个过期时间
     * @param cardEntity
     * @param couponEntity
     * @return
     */
    public Map compareValid(UserCardEntity cardEntity,CouponEntity couponEntity)
    {
        Map<String, Object> map=new HashMap<>();
        System.out.println(cardEntity.getValidDate().compareTo(couponEntity.getEndTime()));
        if(cardEntity.getValidDate().compareTo(couponEntity.getEndTime())<0)
        {
            map.put("type","card");
            UserCard card=this.cardService.queryUserCard(cardEntity.getUserId(), cardEntity.getCardId());
            if(!StringUtil.isNullOrEmpty(card))
            {
                card.setCard(this.cardService.queryCardByCardId(cardEntity.getCardId()));
                card.setCardOrder(cardOrderService.queryOrderInfoByUcId(cardEntity.getUcId()));
                map.put("cardInfo",card);
            }
            return map;
        }else{
            map.put("type","coupon");
            map.put("couponInfo",userCouponService.getUserCouponByIdAndUserId(Integer.parseInt(couponEntity.getCouponId()),couponEntity.getUserId()));
            return map;
        }
    }


    @ApiOperation(
            value = "查询该用户是否有正在进行的订单",
            notes = "小程序-查询该用户是否有正在进行的订单",
            produces = "application/json",
            response = ModelMap.class
    )
    @RequestMapping(
            value = {"/v1/user_washing"},
            method = {RequestMethod.GET},
            produces = {"application/json; charset=utf-8"}
    )
    @ResponseBody
    public ModelMap queryUserWashingOrder(HttpServletRequest request) {
        String sessionId = request.getHeader("authorization");
        UserInfo user = this.wxService.getUserInfoBySessionId(sessionId);
        System.out.println("查询用户：userId="+user.getUserId());
        if (user == null) {
            return    ReturnUtil.ErrorWash("没有洗车订单");
        }
        List<OrderInfo> orderInfoList = this.statisticService.queryUserWashingOrder(user.getUserId());
        if (orderInfoList.isEmpty()) {
            return   ReturnUtil.ErrorWash("没有洗车订单");
        }
        System.out.println("查询结果：orderInfoList="+orderInfoList);
//        if(this.orderService.orderScheduled(orderInfoList.get(0).getOrderSn())==1)
//        {
//            return   ReturnUtil.ErrorWash("没有洗车订单");
//        }
        return ReturnUtil.SuccessWash("查询到尚未结束的洗车订单",orderInfoList.get(0).getOrderSn(),orderInfoList.get(0).getMachineId().toString(),orderInfoList.get(0).getServiceId().toString());
    }


    @ApiOperation(
            value = "查询用户创建的洗车订单",
            notes = "后台-订单相关接口",
            produces = "application/json",
            response = ModelMap.class
    )
    @RequestMapping(
            value = {"/v1/getWashOrder"},
            method = {RequestMethod.GET},
            produces = {"application/json; charset=utf-8"}
    )
    @ResponseBody
    public ModelMap getWashOrder(@RequestParam @ApiParam String userId) {
        String sessionId = request.getHeader("authorization");
        UserInfo user = this.wxService.getUserInfoBySessionId(sessionId);
        return ReturnUtil.Success(ResultState.QUERY_USER_ORDERS_SUCCESS.getMsg(), this.statisticService.queryUserOrder(userId,null));
    }

    @ApiOperation(
            value = "通过订单id查询订单信息",
            notes = "小程序-订单相关接口",
            produces = "application/json",
            response = ModelMap.class
    )
    @ApiImplicitParam(
            name = "orderSn",
            value = "订单id",
            required = true,
            dataType = "String"
    )
    @RequestMapping(
            value = {"/v1/wash_order"},
            method = {RequestMethod.GET},
            produces = {"application/json; charset=utf-8"}
    )
    @ResponseBody
    public ModelMap queryOrder(@RequestParam("orderSn") String orderSn, HttpServletRequest request) {
        OrderInfo order = this.statisticService.queryOrderInfoByOrderSn(orderSn);
        if(order == null){
            logger.info(orderSn);
            return ReturnUtil.Error(ResultState.ORDER_NOT_EXIST.getMsg());
        }

        RateInfo info = null;
        try {
            info = order.getRateInfo();

            if(info != null ){
                String [] comm = info.getComment().split(",");
                String [] content = new String[comm.length];
                for (int i = 0; i <comm.length ; i++) {
                    content[i] = info .getContent()[Integer.valueOf(comm[i])];
                }
                info.setContent(content);
            }
        } catch (Exception e) {
            //e.printStackTrace();
            logger.info("获取订单评论异常！！");
        }
        String mobile ="";
        try{
            mobile = order.getUserInfo().getMobile() ==null?"":order.getUserInfo().getMobile();
        }catch (Exception e){
            logger.info("没有获取到手机号！！");
        }
        List<OrderVO> ls = new ArrayList<>();

        OrderVO rderVO = null;

        if(order.getCreateTime()!= null){
            rderVO = new OrderVO(1,mobile,"创建订单",order.getCreateTime());
            ls.add(rderVO);
        }

        if(order.getPayTime()!= null){
            rderVO = new OrderVO(2,mobile,"支付订单",order.getPayTime());
            ls.add(rderVO);
        }

        if(order.getStartTime()!= null){
            rderVO = new OrderVO(3,mobile,"开始洗车",order.getStartTime());
            ls.add(rderVO);
        }
        if(order.getEndTime()!=null){
            rderVO = new OrderVO(4,mobile,"洗车完成",order.getEndTime());
            ls.add(rderVO);

        }
        if(info != null ){
            rderVO = new OrderVO(5,mobile,"评价订单",order.getEndTime());
            ls.add(rderVO);
        }

        Collections.reverse(ls);
        order.setRecords(ls);
        return order == null ? ReturnUtil.Error(ResultState.ORDER_NOT_EXIST.getMsg()) : ReturnUtil.Success(ResultState.QUERY_USER_ORDERS_SUCCESS.getMsg(), order);
    }

    @ApiOperation(
            value = "查询用户未完成的订单",
            notes = "小程序-订单相关接口",
            produces = "application/json",
            response = ModelMap.class
    )
    @RequestMapping(
            value = {"/v1/user_unfinished_orders"},
            method = {RequestMethod.GET},
            produces = {"application/json; charset=utf-8"}
    )
    @ResponseBody
    public ModelMap queryUserUnfinishedOrders(HttpServletRequest request,
                                              @RequestParam(value = "machineId",required = false) Integer machineId ) {
        String sessionId = request.getHeader("authorization");
        UserInfo user = this.wxService.getUserInfoBySessionId(sessionId);
        System.out.println("参数为：machineId="+machineId+",查询用户：userId="+user.getUserId());

        return user == null ? ReturnUtil.Error(ResultState.GET_USER_INFO_FAILED.getMsg()) : ReturnUtil.Success(ResultState.QUERY_USER_ORDERS_SUCCESS.getMsg(), this.statisticService.queryUserUnfinishedOrders(user.getUserId(),machineId));
    }

    @ApiOperation(
            value = "pc-查询门店下所有的订单信息",
            notes = "管理端-订单管理",
            produces = "application/json",
            response = ModelMap.class
    )
    @ApiImplicitParams({@ApiImplicitParam(
            name = "machineId",
            value = "订单id",
            required = true,
            dataType = "Integer"
    ), @ApiImplicitParam(
            name = "PageSize",
            value = "每页显示的订单数，默认为20",
            required = false,
            dataType = "Integer"
    ), @ApiImplicitParam(
            name = "Page",
            value = "页数，从1开始",
            required = false,
            dataType = "Integer"
    )})
    @RequestMapping(
            value = {"/v1/machine_orders"},
            method = {RequestMethod.GET},
            produces = {"application/json; charset=utf-8"}
    )
    @ResponseBody
    public ModelMap queryMachineIdOrders(@RequestParam("machineId") int machineId,@RequestParam("partnerId") Integer partnerId, @RequestParam(value = "PageSize",defaultValue = "10") Integer pageSize, @RequestParam(value = "page",defaultValue = "1") Integer pageNum) {
//        if(!(request.getSession().getAttribute("ispartnerId") ==null)) {
//            partnerId = Integer.parseInt(request.getSession().getAttribute("ispartnerId").toString());
//        }
        Partner partner=this.partnerService.getPartnerById(partnerId);
        if(partner.getIs_dataer()==1)
        {
            Pagination<OrderInfo> orders = this.statisticService.queryOrderInfoWithPagination(Collections.singletonList(machineId), pageNum, pageSize,partner.getMajor_account());
            return ReturnUtil.Success(ResultState.QUERY_MACHINE_ORDERS_SUCCESS.getMsg(), orders);
        }
        Pagination<OrderInfo> orders = this.statisticService.queryOrderInfoWithPagination(Collections.singletonList(machineId), pageNum, pageSize,partnerId);
        return ReturnUtil.Success(ResultState.QUERY_MACHINE_ORDERS_SUCCESS.getMsg(), orders);
    }


    @ApiOperation(
            value = "商家端-查询门店下所有的订单信息",
            notes = "商家端-订单管理",
            produces = "application/json",
            response = ModelMap.class
    )
    @ApiImplicitParams({@ApiImplicitParam(
            name = "machineId",
            value = "订单id",
            required = true,
            dataType = "Integer"
    ), @ApiImplicitParam(
            name = "PageSize",
            value = "每页显示的订单数，默认为20",
            required = false,
            dataType = "Integer"
    ), @ApiImplicitParam(
            name = "Page",
            value = "页数，从1开始",
            required = false,
            dataType = "Integer"
    )})
    @RequestMapping(
            value = {"/v1/store/machine_orders"},
            method = {RequestMethod.GET},
            produces = {"application/json; charset=utf-8"}
    )
    @ResponseBody
    public ModelMap queryMachineIdOrders(@RequestParam("machineId") int machineId,@RequestParam(value = "PageSize",defaultValue = "-1") int pageSize, @RequestParam(value = "page",defaultValue = "-1") int pageNum) {

        GetSessionConfig config=new GetSessionConfig();
        Map<String,String> map= config.getStorePartnerId("查看主页统计",request);
        int partnerId=Integer.parseInt(map.get("partnerId"));
        Pagination<OrderInfo> orders = this.statisticService.queryOrderInfoWithPagination(Collections.singletonList(machineId), pageNum, pageSize,partnerId);
        return ReturnUtil.Success(ResultState.QUERY_MACHINE_ORDERS_SUCCESS.getMsg(), orders);
    }
    @ApiOperation(
            value = "pc-查询所有洗车订单信息",
            notes = "管理端-订单管理",
            produces = "application/json",
            response = ModelMap.class
    )
    @ApiImplicitParams({@ApiImplicitParam(
            name = "filterCondition",
            value = "查询条件 {'Page'：1，'orderSn':'','userId','','sTime':'202-01-20','eTime':'202-01-20','machineId':51,'PageSize'：20,'mobile':'18121212321','payWayCode':'支付方式1--微信； 2--会员卡','consumed':'消费状态 0 未消费 1 以消费 2 消费中急停'}",
            required = true,
            dataType = "Map"
    )})
    @RequestMapping(
            value = {"/v1/machine_orders"},
            method = {RequestMethod.POST},
            produces = {"application/json; charset=utf-8"}
    )
    @ResponseBody
    public ModelMap queryAllOrders(@RequestBody Map<String, Object> filterCondition) {
        if(filterCondition.containsKey("Page")&&filterCondition.containsKey("PageSize")){
            if(filterCondition.containsKey("sTime")&&filterCondition.containsKey("eTime")){
                String sTime = filterCondition.get("sTime").toString();
                Date sdate = DateUtil.stringToDate(sTime,"yyyy-MM-dd");
                filterCondition.put("sTime",sdate);

                String eTime = filterCondition.get("eTime").toString();
                Date edate = DateUtil.stringToDate(eTime,"yyyy-MM-dd");
                filterCondition.put("eTime",edate);

            }

            PageInfo<OrderInfo> orders = this.orderService.queryAllOrdersByCondition(filterCondition);
            return ReturnUtil.Success(ResultState.QUERY_MACHINE_ORDERS_SUCCESS.getMsg(), orders);
        }
        return ReturnUtil.Error("无效参数");
    }



    @ApiOperation(
            value = "小程序-删除用户订单",
            notes = "小程序-删除用户订单",
            produces = "application/json",
            response = ModelMap.class
    )
    @RequestMapping(
            value = {"/v1/userOrder/delate"},
            method = {RequestMethod.GET},
            produces = {"application/json; charset=utf-8"}
    )
    @ResponseBody
    public ModelMap delete(@RequestParam String orderSn,HttpServletRequest request) {


        String sessionId = request.getHeader("authorization");
        UserInfo user = this.wxService.getUserInfoBySessionId(sessionId);
        if( user == null ){
            ReturnUtil.Error(ResultState.GET_USER_INFO_FAILED.getMsg());
        }
        OrderInfo orderInfo  = orderService.queryOrderInfoByOrderSn(orderSn);
        if( orderInfo == null ){
            ReturnUtil.Error("无效订单");
        }

        if( orderInfo.getPayStatus() ==2 && orderInfo.getConsumed() == 0 ){
            ReturnUtil.Error("订单未消费！");
        }
//        int rows = orderService.deleteOrder(orderInfo);
//        if(rows>0){
//            return  ReturnUtil.Success("删除成功");
//        }
//        return ReturnUtil.Success("删除失败");
        return ReturnUtil.Success("删除成功");

    }


    @ApiOperation(
            value = "pc端-删除用户订单",
            notes = "pc端-删除用户订单",
            produces = "application/json",
            response = ModelMap.class
    )
    @RequestMapping(
            value = {"/v1/userOrder/pcDelate"},
            method = {RequestMethod.GET},
            produces = {"application/json; charset=utf-8"}
    )
    @ResponseBody
    public ModelMap pcDelate(@RequestParam String orderSn,HttpServletRequest request) {
        OrderInfo orderInfo  = orderService.queryOrderInfoByOrderSn(orderSn);
        if( orderInfo == null ){
            ReturnUtil.Error("无效订单");
        }

        if( orderInfo.getPayStatus() ==2 && orderInfo.getConsumed() == 0 ){
            ReturnUtil.Error("订单未消费！");
        }
        int rows = orderService.deleteOrderLyj(orderInfo);
        if(rows>0){
            return  ReturnUtil.Success("删除成功");
        }
        return ReturnUtil.Success("删除失败");
    }



    @ApiOperation(
            value = "小程序-计时订单完成调用",
            notes = "小程序-计时订单完成调用",
            produces = "application/json",
            response = ModelMap.class
    )
    @RequestMapping(
            value = {"/v1/order/finishOrder"},
            method = {RequestMethod.GET},
            produces = {"application/json; charset=utf-8"}
    )
    @ResponseBody
    public ModelMap finishOrder(@RequestParam String orderSn,HttpServletRequest request) {


        String sessionId = request.getHeader("authorization");
        UserInfo user = this.wxService.getUserInfoBySessionId(sessionId);
        if( user == null ){
            ReturnUtil.Error(ResultState.GET_USER_INFO_FAILED.getMsg());
        }
        OrderInfo orderInfo  = orderService.queryOrderInfoByOrderSn(orderSn);
        if( orderInfo == null ){
            ReturnUtil.Error("无效订单");
        }
        int rows = orderService.finishOrder(orderSn);
        if(rows>0){
            return  ReturnUtil.Success("删除成功");
        }
        return ReturnUtil.Success("删除失败");
    }

    @ApiOperation(
            value = "小程序赠送朋友---查询朋友是否存在",
            notes = "小程序---朋友相关接口",
            produces = "application/json",
            response = ModelMap.class
    )
    @RequestMapping(
            value = {"/v1/checkIsMoblie"},
            method = {RequestMethod.GET},
            produces = {"application/json; charset=utf-8"}
    )
    @ResponseBody
    public ModelMap queryUserOrders(HttpServletRequest request,String mobile) {
        String sessionId = request.getHeader("authorization");
        UserInfo user = this.wxService.getUserInfoBySessionId(sessionId);
        return user == null ? ReturnUtil.Error(ResultState.USER_NOT_EXIST.getMsg()) : ReturnUtil.Success(ResultState.USER_EXIST.getMsg(), this.userInfoService.findByMobile(mobile));
    }

    @ApiOperation(
            value = "小程序会员卡赠送朋友",
            notes = "会员卡赠送朋友",
            produces = "application/json",
            response = ModelMap.class
    )
    @RequestMapping(
            value = {"/v1/sendCard"},
            method = {RequestMethod.GET},
            produces = {"application/json; charset=utf-8"}
    )
    @ResponseBody
    public ModelMap sendCardBy(HttpServletRequest request,String mobile,String ucId) {
//        String sessionId = request.getHeader("authorization");
        //赠送的人
//        UserInfo user = this.wxService.getUserInfoBySessionId(sessionId);
        //要赠送的朋友用户信息
        UserInfo userInfo=this.userInfoService.findByMobile(mobile);
        if(userInfo==null)
        {
            ReturnUtil.Error("朋友信息不存在");
        }
//       根据ucId查找会员卡编号
        CardOrder cardOrder=this.cardService.queryCardOrder(ucId);
        if(cardOrder==null)
        {
            ReturnUtil.Error("会员卡信息不存在");
        }
        if(cardOrder.getIsSend()!=0)
        {
            ReturnUtil.Error("该会员卡不能再赠送");
        }
        //不用更改会员卡记录表中的会员卡cardId,判断会员卡是否已经使用
        CardRecord cardRecord=this.cardRecordDao.getCardRecordByUcid(cardOrder.getUcId());
        if(cardRecord.getFirstTimes()!=null&&cardRecord.getRefundTime()!=null)
        {
            ReturnUtil.Error("该会员卡已使用,不可赠送");
        }
        //会员卡订单信息中的isSend为1,即为已赠送给好友的会员卡订单
        cardOrder.setIsSend(1);
        //拿出会员卡对应的ucId
        int flag= this.userCardMapper.updateSendUserCard(ucId,userInfo.getUserId());
        return flag == 0 ? ReturnUtil.Error("会员卡赠送失败") : ReturnUtil.Success("会员卡赠送成功");
    }







    public static void main(String[] args) {

//       String time="07:00:00,23:00:00";
//        String[] timeArray=time.split(",");
//        String s=DateUtil.format(DateUtil.getSysTime(),"yyyy-MM-dd")+" "+timeArray[0];
//
//        String s1=DateUtil.format(DateUtil.getSysTime(),"yyyy-MM-dd")+" "+timeArray[1];
        //System.out.println(DateUtil.strToDate(s1).getTime()>=new Date().getTime());

    }


}
